package org.jeecg.modules.cascv.kafka;

import cn.hutool.core.util.RandomUtil;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cwenao
 * @version $Id KafkaConfig.java, v 0.1 2017-01-20 9:51 cwenao Exp $$
 */

@Configuration
@EnableKafka
@ConditionalOnProperty(
        value = {"bootcwenao.kafka.enable"},
        matchIfMissing = true
)
public class KafkaProducersConfig {
    @Value("${bootcwenao.kafka.binder.brokers}")
    private String brokers;
    @Value("${bootcwenao.kafka.producer.batch-size}")
    private Integer batchSize;
    @Value("${bootcwenao.kafka.producer.buffer-memory}")
    private Integer bufferMemory;
    @Value("${bootcwenao.kafka.producer.linger}")
    private Integer linger;

    @Bean("kafkaTemplate")
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

    public ProducerFactory<String, String> producerFactory() {

        // set the producer properties
        Map<String, Object> properties = new HashMap<>();
        //用户设定，用于跟踪记录消息，默认”“
        properties.put(ProducerConfig.CLIENT_ID_CONFIG, "CLIENT_P" + RandomUtil.randomInt(100));
        //指定Kafka集群所需的broker地址清单，默认“”
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
//        properties.put(ProducerConfig.RECEIVE_BUFFER_CONFIG, 0);
        //指定ProducerBatch内存区域的大小，默认16kb
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
//指定ProducerBatch在延迟多少毫秒后再发送，但如果在延迟的这段时间内batch的大小已经到了batch.size设置的大小，那么消息会被立即发送，不会再等待，默认值0
        properties.put(ProducerConfig.LINGER_MS_CONFIG, linger);
//生产者客户端中用于缓存消息的缓存区大小，默认32MB
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
        //key的序列化方式
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //value序列化类方式
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
//        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
//        properties.put("value.serializer", "com.cascv.device.kafka.EncodeingKafka");

        return new DefaultKafkaProducerFactory<String, String>(properties);
    }
}